package com.fulihui.usercore.core.repository.impl;

import com.fulihui.usercore.biz.conv.UserAddressConv;
import com.fulihui.usercore.core.repository.UserAddressRepository;
import com.fulihui.usercore.dal.dataobj.UserAddressDO;
import com.fulihui.usercore.dal.mapper.UserAddressMapper;
import com.fulihui.usercore.dto.UserAddressDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Willard.Hu on 2016/5/24.
 */
@Repository
public class UserAddressRepositoryImpl implements UserAddressRepository {
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private UserAddressConv   userAddressConv;

    @Override
    public long create(UserAddressDTO userAddressDTO) {
        UserAddressDO userAddressDO = userAddressConv.toDO(userAddressDTO);
        // 同一个时间戳请求做幂等性处理，
        // XXX 后续按实际情况考虑是否要用锁
        UserAddressDO condition = new UserAddressDO();
        condition.setUserId(userAddressDTO.getUserId());
        condition.setTimestamp(userAddressDTO.getTimestamp());
        List<UserAddressDO> rsList = userAddressMapper.query(condition);
        if (CollectionUtils.isEmpty(rsList)) {
            userAddressMapper.insert(userAddressDO);
        }
        return userAddressDO.getId();
    }

    @Override
    public boolean update(UserAddressDTO userAddressDTO) {
        UserAddressDO userAddressDO = userAddressConv.toDO(userAddressDTO);
        return userAddressMapper.update(userAddressDO);
    }

    @Override
    public boolean cancelUserAddrDefault(String userId) {
        return userAddressMapper.cancelUserAddrDefault(userId);
    }

    @Override
    public boolean delete(long id, String userId) {
        return userAddressMapper.delete(id, userId);
    }

    @Override
    public UserAddressDTO queryByPK(long id, String userId) {
        UserAddressDO userAddressDO = userAddressMapper.queryByPK(id, userId);
        return userAddressConv.toDTO(userAddressDO);
    }

    @Override
    public List<UserAddressDTO> queryByUser(String userId) {
        UserAddressDO condition = new UserAddressDO();
        condition.setUserId(userId);
        List<UserAddressDO> doList = userAddressMapper.query(condition);
        return userAddressConv.toList(doList);
    }
}
